package com.atcumt.Thread.ProductorAndConsumer;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {

    private Queue<Object> queue;
    private int max = 16;
    private ReentrantLock lock = new ReentrantLock();
    private Condition notEmpty = lock.newCondition();
    private Condition notFull = lock.newCondition();

    public ConditionDemo(int size) {
        this.max = size;
        queue = new LinkedList<>();
    }

    public void put(Object obj) throws InterruptedException {

        lock.lock();
        try {
            while (queue.size() == max) {
                notFull.await(); // 阻塞生产者线程并释放 Lock
            }
            queue.add(obj);
            notEmpty.signalAll(); // 通知正在等待的所有消费者并唤醒它们

        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {

        lock.lock();
        try {
            while (queue.size() == 0) {
                notEmpty.await(); // 阻塞消费者线程并释放 Lock
            }

            Object item = queue.remove();
            notFull.signalAll(); // 通知正在等待的生产者并唤醒它们
            return item;
        } finally {
            lock.unlock();
        }
    }
}
